package com.xinya.wanandroidclient.ui.tab

import android.os.Bundle
import android.util.Log
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.xinya.wanandroidclient.Constants
import com.xinya.wanandroidclient.R
import com.xinya.wanandroidclient.base.BaseFragment
import com.xinya.wanandroidclient.bean.ProjectClassificationBean
import com.xinya.wanandroidclient.databinding.FragmentTabBinding
import com.xinya.wanandroidclient.ui.articleList.ArticleListFragment

/**
 *
 * @ClassName:      TabFragment
 * @Description:     java类作用描述
 * @Author:         mhzhuxinya@163.com
 * @UpdateRemark:   更新说明：
 * @Version:        1.0
 */
class TabFragment : BaseFragment() {

    companion object {
        private const val TAG = "TabFragment"
    }

    override fun getLayoutId() = R.layout.fragment_tab

    // PROJECT_TYPE  WX_ACCOUNT_TYPE
    private val fragmentType by lazy {
        arguments?.getInt("type", 0) ?: 0
    }

    private val tabViewModel by lazy {
        getFragmentVieModel(TabViewModel::class.java)
    }

    private lateinit var dataBinding: FragmentTabBinding
    override fun initDataBinding(binding: ViewDataBinding?) {
        dataBinding = binding as FragmentTabBinding
    }

    override fun init(savedInstanceState: Bundle?) {
        // 进行数据请求
        if (fragmentType != Constants.PROJECT_TYPE && fragmentType != Constants.WX_ACCOUNT_TYPE) {
            return
        }
        // 请求数据
        tabViewModel.getTabList(fragmentType!!)
    }


    override fun observer() {
        // 监听数据变化
        tabViewModel.apply {
            tabListLiveData.observe(this@TabFragment) {
                initViewPager(it)
            }
        }

    }

    private fun initViewPager(pagerList: MutableList<ProjectClassificationBean>) {

        // 初始化View
        val tabLayoutView = dataBinding.tabTab
        val viewPagerView = dataBinding.tabViewpager

        viewPagerView.apply {
            adapter = object : FragmentStateAdapter(this@TabFragment) {
                override fun getItemCount() = pagerList.size

                override fun createFragment(position: Int): Fragment {
                    return ArticleListFragment().apply {
                        arguments = Bundle().apply {
                            putInt("type", fragmentType)
                            putInt("tabId", pagerList[position].id)
                            putString("name", pagerList[position].name)
                        }
                    }
                }
            }
            offscreenPageLimit = 1
        }

        TabLayoutMediator(tabLayoutView, viewPagerView) { tab: TabLayout.Tab, position: Int ->
            tab.text = pagerList[position].name
        }.attach()

    }

    override fun onClick() {

    }
}